package com.tz.dao;

import com.tz.entity.Category;
import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 *
 */
@Repository
@Transactional
public class CategoryDaoImpl implements CategoryDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Category save(Category category) {
        this.getSession().save(category);
        return category;
    }

	@Override
    public List<Category> getAll() {
        String hql = "select c from Category c";//from实体类而不是表名
        return this.getSession().createQuery(hql).list();
    }

    @Override
    public List<Category> getByLevel(int level) {
        //String hql = "select c from Category c where c.level:level order by c.seq";
        List<Category> list = this.getSession().createCriteria(Category.class)
                .add(Restrictions.eq("level", level))
                .addOrder(Order.asc("seq"))
                .list();
        for(Category c : list){
            int i =c.getChildren().size();
        }
        return list;
    }
}
